package cn.yunhe.interceptor;

import cn.yunhe.control.CalculatorAction;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

public class CalculatorInterceptor extends MethodFilterInterceptor {

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        CalculatorAction action = (CalculatorAction) invocation.getAction();
        double num = action.getNum2();
        HttpServletRequest request =ServletActionContext.getRequest();
        String type = request.getHeader("X-Requested-With");
        String method = invocation.getProxy().getMethod().toLowerCase();
        if ("XMLHttpRequest".equalsIgnoreCase(type)){
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            if (method.equals("div") && num == 0) {
                out.print("被除数不能为0");
                out.flush();
                return null;
            } else {
                return invocation.invoke();
            }
        }else {
            return invocation.invoke();
        }

    }

}
